package com.ming.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.ContentType;
import com.ming.common.CodeMsg;
import com.ming.common.Result;
import com.ming.common.config.file.FileService;
import com.ming.common.config.file.UploadProperties;
import com.ming.common.validator.ValidatorUtil;
import com.ming.domain.BookE;
import com.ming.from.BookEForm;
import com.ming.query.BookEQuery;
import com.ming.query.BookQuery;
import com.ming.service.BookEService;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:何元才
 * @Desc:
 * @data:2021-05-07 10:22
 */
@RestController
@RequestMapping("ebook")
public class BookEController {

    @Autowired
    private BookEService bookEService;

    @Autowired
    private FileService fileService;

    @Autowired
    private UploadProperties uploadProperties;

    /**
     * 分页查询
     * @param query
     * @return
     */
    @GetMapping("page.do")
    public Object page(BookEQuery query) {
        Result rs = bookEService.queryPage(query);
        return rs;
    }

//    /**
//     * 新增
//     * @param bookEForm
//     * @return
//     */
//    @PostMapping("add.do")
//    public Object  add(BookEForm bookEForm) throws IOException {
////        MultipartFile file = (MultipartFile) bookEForm.getFile();
//        File file = bookEForm.getFile();
//        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
//        MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
//
//        // 原始文件的名称-----文件的后缀名
//        String originalFilename = bookEForm.getEName();
//        // 文件的大小---限制文件的大小
//        long size = multipartFile.getSize();
//
//        // 文件的输入流 --- 获取文件的数据
//        String filePath = "";
//        Map<String, String> result = new HashMap<>();
//        try {
//            inputStream = multipartFile.getInputStream();
//            // naodi.jpg
//            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//            filePath = fileService.uploadFile(inputStream, size, extName);
//            result.put("url", filePath);
//            result.put("name", originalFilename);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }        bookEForm.setUrl(filePath);
//        Result rs = bookEService.add(bookEForm);
//        return rs;
//    }

    /**
     * 检查入库
     * @param eId
     * @return
     */
    @GetMapping("check.do")
    public Object check(Integer eId) {
        Result rs = bookEService.check(eId);
        return rs;
    }

    /**
     * 上传文件
     * @return
     */
    @RequestMapping("upload.do")
    public Object upload(MultipartFile file, HttpServletRequest request) {
        String book = request.getServletContext().getRealPath("book");
        //产生文件名称
        String times = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
        //获取文件后缀
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String extName = FileUtil.extName(originalFilename);
        //文件保存得路径
        String path = book+ File.separator+times+"."+extName;
        //文件得URL路径
        String url = "book/"+times+"."+extName;
        try {
            //将文件保存
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(CodeMsg.BOOK_SAVE_ERROR);
        }
        return new Result(url);
    }

    @RequestMapping("add.do")
    public Object add(BookEForm bookEForm) {
        ValidatorUtil.validator(bookEForm);
        Result rs = bookEService.add(bookEForm);
        return rs;
    }


//    @PostMapping("upload.do")
//    public Object uploadFile( MultipartFile file) {
//
//        // 原始文件的名称-----文件的后缀名
//        String originalFilename = file.getOriginalFilename();
//
//        // 得到上传文件的类型---mvc 会自动的解析到文件的类型--限制文件的类型
//        String contentType = file.getContentType();
//        if (!uploadProperties.getAllowTypes().contains(contentType)) {
//            return new Result(400, "文件不支持");
//        }
//        // 文件的大小---限制文件的大小
//        long size = file.getSize();
//
//        if ((uploadProperties.getAllowSize() * 1024L * 1024) <= size) {
//            return new Result(400, "文件大小超出限制");
//        }
////        // 文件的输入流 --- 获取文件的数据
//        InputStream inputStream = null;
//        String filePath = "";
//        Map<String, String> result = new HashMap<>();
//        try {
//            inputStream = file.getInputStream();
//            // naodi.jpg
//            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//            filePath = fileService.uploadFile(inputStream, size, extName);
//            result.put("url", filePath);
//            result.put("name", originalFilename);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
////        byte[] bytes = file.getBytes();
//
//        /// 文件上传成功后, 我们给别人返回一个能访问文件的url 地址
//        return filePath;
//    }
//
//    private FileItem createFileItem(File file, String fieldName) {
//        FileItemFactory factory = new DiskFileItemFactory(16, null);
//        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
//        int bytesRead = 0;
//        byte[] buffer = new byte[8192];
//        try {
//            FileInputStream fis = new FileInputStream(file);
//            OutputStream os = item.getOutputStream();
//            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
//                os.write(buffer, 0, bytesRead);
//            }
//            os.close();
//            fis.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return item;
//    }



}
